from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

# 初始化 Flask 应用
app = Flask(__name__)

# 配置 SQLite 数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.db'  # SQLite 数据库
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 初始化 SQLAlchemy
db = SQLAlchemy(app)


# 学生信息模型
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    age = db.Column(db.Integer, nullable=False)
    score = db.Column(db.Float, nullable=False)

    def __repr__(self):
        return f'<Student {self.name}>'


# 创建数据库（只需第一次运行时）
with app.app_context():
    db.create_all()


# 首页，显示所有学生信息
@app.route('/')
def index():
    students = Student.query.all()  # 获取所有学生数据
    return render_template('index.html', students=students)


# 添加学生信息
@app.route('/add', methods=['GET', 'POST'])
def add_student():
    if request.method == 'POST':
        name = request.form['name']
        age = request.form['age']
        score = request.form['score']

        # 创建新的学生对象
        new_student = Student(name=name, age=int(age), score=float(score))

        # 将学生添加到数据库
        db.session.add(new_student)
        db.session.commit()

        return redirect(url_for('index'))  # 添加后返回首页

    return render_template('add_student.html')  # GET 请求时显示添加学生页面


# 删除学生信息
@app.route('/delete/<int:id>', methods=['GET', 'POST'])
def delete_student(id):
    student = Student.query.get_or_404(id)  # 获取学生对象
    db.session.delete(student)  # 删除该学生
    db.session.commit()  # 提交修改
    return redirect(url_for('index'))  # 删除后返回首页


# 启动 Flask 应用
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

